package com.game.gateway.server.handler;


import com.game.netty.game.GameMessageService;
import com.game.netty.game.common.GameMessagePackage;
import com.game.netty.game.message.FirstMsgRequest;
import com.game.netty.game.message.FirstMsgResponse;
import com.game.netty.game.message.SecondMsgRequest;
import com.game.netty.game.message.SecondMsgResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestGameMessageHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(TestGameMessageHandler.class);
    private GameMessageService messageService;

    public TestGameMessageHandler(){};
    public TestGameMessageHandler(GameMessageService messageService) {
        this.messageService = messageService;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("success in ...............");
        GameMessagePackage gameMessagePackage = (GameMessagePackage) msg;
        int messageId = gameMessagePackage.getHeader().getMessageId();
        if (messageId == 10001) {
            FirstMsgRequest request = new FirstMsgRequest();
            request.read(gameMessagePackage.getBody());
            logger.debug("接收到客户端消息：{}", request.getValue());
            System.out.println(request.getValue());
            FirstMsgResponse response = new FirstMsgResponse();
            response.setServerTime(System.currentTimeMillis());
            GameMessagePackage returnPackage = new GameMessagePackage();
            returnPackage.setHeader(response.getHeader());
            returnPackage.setBody(response.body());
            ctx.writeAndFlush(returnPackage);
        } else if (messageId == 10002) {
            SecondMsgRequest request = (SecondMsgRequest) messageService.getRequestInstanceByMessageId(messageId);
            request.read(gameMessagePackage.getBody());
            logger.debug("收到request3:{}", request);
            System.out.println(request);
            SecondMsgResponse response = new SecondMsgResponse();
            response.getBodyObj().setResult1(System.currentTimeMillis());
            response.getBodyObj().setResult2("服务器回复");
            GameMessagePackage returnPackage = new GameMessagePackage();
            returnPackage.setHeader(response.getHeader());
            returnPackage.setBody(response.body());
            ctx.writeAndFlush(returnPackage);
        }
    }
}
